package com.example.loginserver.controller;

import com.example.loginserver.utils.JwtUtils;
import com.example.loginserver.utils.QRCodeUtil;
import com.example.loginserver.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.google.zxing.WriterException;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.UUID;

import static com.example.loginserver.domain.Constant.AUTH_TOKEN_PREFIX;
import static com.example.loginserver.domain.Constant.LOGIN_QRCODE;

@RestController
public class QrCodeController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping(LOGIN_QRCODE)
    public Result loginQrCode(HttpServletResponse response) throws WriterException, IOException {

        String token = JwtUtils.createToken(UUID.randomUUID().toString().substring(0, 10));


        // 禁止图像缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        BufferedImage image = QRCodeUtil.createImage(token);

        // 创建二进制的输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 将图像输出到输出流中。
        ImageIO.write(image, "png", outputStream);

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();


//        对数据流中的图片进行 base64 编码
        String base64Img = encoder.encode(outputStream.toByteArray());

        Result r = Result.OK();
//        将编码完成的图片放入到响应中
        r.put("img", "data:image/png;base64," + base64Img);
//        还没有被认证的 jwtToken
        r.put("unAuthenticatedJwtToken", token);
        return r;
    }

    /**
     * 手机扫描二维码登陆
     *
     * @return
     */

    @GetMapping("/phoneScanQrCodeLogin")
    public Result phoneScanQrCodeLogin(
            @RequestParam String unAuthenticatedJwtToken,
            Authentication authentication
    ) throws JsonProcessingException {


        ObjectMapper objectMapper = new ObjectMapper();


//      创建redis中用户的 key
        String key = AUTH_TOKEN_PREFIX + JwtUtils.parseToken(unAuthenticatedJwtToken).getSubject();

        redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(authentication.getPrincipal()));

        redisTemplate.expire(key, Duration.ofMinutes(5));

        return Result.OK();
    }


}
